<template>
  <div class="monitoring-dashboard">
    <!-- 状态概览卡片 -->
    <div class="status-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="status-card online">
            <div class="card-content">
              <div class="icon">
                <el-icon><Monitor /></el-icon>
              </div>
              <div class="info">
                <div class="value">{{ summary.online_hosts }}</div>
                <div class="label">在线主机</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="status-card offline">
            <div class="card-content">
              <div class="icon">
                <el-icon><Warning /></el-icon>
              </div>
              <div class="info">
                <div class="value">{{ summary.offline_hosts }}</div>
                <div class="label">离线主机</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="status-card warning">
            <div class="card-content">
              <div class="icon">
                <el-icon><WarningFilled /></el-icon>
              </div>
              <div class="info">
                <div class="value">{{ summary.warning_hosts }}</div>
                <div class="label">告警主机</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="status-card critical">
            <div class="card-content">
              <div class="icon">
                <el-icon><CircleCloseFilled /></el-icon>
              </div>
              <div class="info">
                <div class="value">{{ summary.critical_hosts }}</div>
                <div class="label">严重告警</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 实时监控图表 -->
    <div class="charts-section">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card>
            <template #header>
              <div class="chart-header">
                <span>CPU使用率趋势</span>
                <el-button-group size="small">
                  <el-button 
                    v-for="range in timeRanges" 
                    :key="range.value"
                    :type="selectedTimeRange === range.value ? 'primary' : ''"
                    @click="changeTimeRange(range.value)"
                  >
                    {{ range.label }}
                  </el-button>
                </el-button-group>
              </div>
            </template>
            <div ref="cpuChart" class="chart-container"></div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card>
            <template #header>
              <span>内存使用率趋势</span>
            </template>
            <div ref="memoryChart" class="chart-container"></div>
          </el-card>
        </el-col>
      </el-row>
      
      <el-row :gutter="20" style="margin-top: 20px;">
        <el-col :span="12">
          <el-card>
            <template #header>
              <span>磁盘使用率</span>
            </template>
            <div ref="diskChart" class="chart-container"></div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card>
            <template #header>
              <span>网络IO</span>
            </template>
            <div ref="networkChart" class="chart-container"></div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 主机列表 -->
    <div class="host-list-section">
      <el-card>
        <template #header>
          <div class="list-header">
            <span>实时主机状态</span>
            <el-switch
              v-model="autoRefresh"
              active-text="自动刷新"
              @change="toggleAutoRefresh"
            />
          </div>
        </template>
        <el-table :data="realtimeData" v-loading="loading">
          <el-table-column prop="hostname" label="主机名" width="150" />
          <el-table-column prop="host_ip" label="IP地址" width="120" />
          <el-table-column label="CPU使用率" width="120">
            <template #default="{ row }">
              <el-progress 
                :percentage="row.cpu_usage" 
                :color="getProgressColor(row.cpu_usage)"
                :show-text="false"
              />
              <span class="progress-text">{{ row.cpu_usage.toFixed(1) }}%</span>
            </template>
          </el-table-column>
          <el-table-column label="内存使用率" width="120">
            <template #default="{ row }">
              <el-progress 
                :percentage="row.memory_usage" 
                :color="getProgressColor(row.memory_usage)"
                :show-text="false"
              />
              <span class="progress-text">{{ row.memory_usage.toFixed(1) }}%</span>
            </template>
          </el-table-column>
          <el-table-column label="磁盘使用率" width="120">
            <template #default="{ row }">
              <el-progress 
                :percentage="row.disk_usage" 
                :color="getProgressColor(row.disk_usage)"
                :show-text="false"
              />
              <span class="progress-text">{{ row.disk_usage.toFixed(1) }}%</span>
            </template>
          </el-table-column>
          <el-table-column label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)">
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="collected_at" label="更新时间" width="180">
            <template #default="{ row }">
              {{ formatTime(row.collected_at) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="{ row }">
              <el-button 
                type="primary" 
                size="small" 
                @click="viewHostDetail(row.host)"
              >
                详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Monitor, Warning, WarningFilled, CircleCloseFilled 
} from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import api from '@/utils/api'
import { monitoringApi } from '@/api/monitoring'

// 响应式数据
const loading = ref(false)
const autoRefresh = ref(true)
const selectedTimeRange = ref('1h')
const refreshInterval = ref<number | null>(null)

// 图表实例
const cpuChart = ref<echarts.ECharts | null>(null)
const memoryChart = ref<echarts.ECharts | null>(null)
const diskChart = ref<echarts.ECharts | null>(null)
const networkChart = ref<echarts.ECharts | null>(null)

// 数据
const summary = reactive({
  total_hosts: 0,
  online_hosts: 0,
  offline_hosts: 0,
  warning_hosts: 0,
  critical_hosts: 0
})

const realtimeData = ref([])
const chartData = reactive({
  cpu: [],
  memory: [],
  disk: [],
  network: []
})

// 时间范围选项
const timeRanges = [
  { label: '1小时', value: '1h' },
  { label: '24小时', value: '24h' },
  { label: '7天', value: '7d' },
  { label: '30天', value: '30d' }
]

// 获取监控摘要
const fetchSummary = async () => {
  try {
    const response = await monitoringApi.getSummary()
    if (response.data.success) {
      Object.assign(summary, response.data.data)
    }
  } catch (error) {
    console.error('获取监控摘要失败:', error)
  }
}

// 获取实时数据
const fetchRealtimeData = async () => {
  try {
    loading.value = true
    const response = await monitoringApi.getRealtimeMetrics()
    if (response.data.success) {
      realtimeData.value = response.data.data
    }
  } catch (error) {
    console.error('获取实时数据失败:', error)
    ElMessage.error('获取实时数据失败')
  } finally {
    loading.value = false
  }
}

// 获取图表数据
const fetchChartData = async (timeRange: string) => {
  try {
    // 这里应该调用实际的API获取图表数据
    // 暂时使用模拟数据
    generateMockChartData()
  } catch (error) {
    console.error('获取图表数据失败:', error)
  }
}

// 生成模拟图表数据
const generateMockChartData = () => {
  const now = new Date()
  const data = []
  
  for (let i = 23; i >= 0; i--) {
    const time = new Date(now.getTime() - i * 60 * 60 * 1000)
    data.push({
      time: time.toLocaleTimeString(),
      cpu: Math.random() * 100,
      memory: Math.random() * 100,
      disk: Math.random() * 100,
      network_in: Math.random() * 1000,
      network_out: Math.random() * 1000
    })
  }
  
  chartData.cpu = data.map(item => [item.time, item.cpu])
  chartData.memory = data.map(item => [item.time, item.memory])
  chartData.disk = data.map(item => [item.time, item.disk])
  chartData.network = data.map(item => [item.time, item.network_in, item.network_out])
}

// 初始化图表
const initCharts = async () => {
  await nextTick()
  
  // CPU图表
  if (cpuChart.value) {
    cpuChart.value.dispose()
  }
  cpuChart.value = echarts.init(document.querySelector('.chart-container'))
  
  // 其他图表初始化...
  updateCharts()
}

// 更新图表
const updateCharts = () => {
  if (!cpuChart.value) return
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: chartData.cpu.map(item => item[0])
    },
    yAxis: {
      type: 'value',
      max: 100,
      axisLabel: {
        formatter: '{value}%'
      }
    },
    series: [{
      name: 'CPU使用率',
      type: 'line',
      smooth: true,
      data: chartData.cpu.map(item => item[1]),
      areaStyle: {
        opacity: 0.3
      },
      lineStyle: {
        color: '#409EFF'
      },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(64, 158, 255, 0.3)' },
          { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
        ])
      }
    }]
  }
  
  cpuChart.value.setOption(option)
}

// 工具函数
const getProgressColor = (value: number) => {
  if (value >= 90) return '#F56C6C'
  if (value >= 70) return '#E6A23C'
  return '#67C23A'
}

const getStatusType = (status: string) => {
  const typeMap = {
    'normal': 'success',
    'warning': 'warning',
    'critical': 'danger'
  }
  return typeMap[status] || 'info'
}

const getStatusText = (status: string) => {
  const textMap = {
    'normal': '正常',
    'warning': '告警',
    'critical': '严重'
  }
  return textMap[status] || '未知'
}

const formatTime = (time: string) => {
  return new Date(time).toLocaleString()
}

const changeTimeRange = (range: string) => {
  selectedTimeRange.value = range
  fetchChartData(range)
}

const toggleAutoRefresh = (enabled: boolean) => {
  if (enabled) {
    startAutoRefresh()
  } else {
    stopAutoRefresh()
  }
}

const startAutoRefresh = () => {
  if (refreshInterval.value) {
    clearInterval(refreshInterval.value)
  }
  refreshInterval.value = setInterval(() => {
    fetchRealtimeData()
    fetchSummary()
  }, 10000) // 10秒刷新一次
}

const stopAutoRefresh = () => {
  if (refreshInterval.value) {
    clearInterval(refreshInterval.value)
    refreshInterval.value = null
  }
}

const viewHostDetail = (hostId: number) => {
  // 跳转到主机详情页面
  console.log('查看主机详情:', hostId)
}

// 生命周期
onMounted(() => {
  fetchSummary()
  fetchRealtimeData()
  fetchChartData(selectedTimeRange.value)
  initCharts()
  
  if (autoRefresh.value) {
    startAutoRefresh()
  }
})

onUnmounted(() => {
  stopAutoRefresh()
  if (cpuChart.value) {
    cpuChart.value.dispose()
  }
  if (memoryChart.value) {
    memoryChart.value.dispose()
  }
  if (diskChart.value) {
    diskChart.value.dispose()
  }
  if (networkChart.value) {
    networkChart.value.dispose()
  }
})
</script>

<style scoped>
.monitoring-dashboard {
  padding: 20px;
}

.status-cards {
  margin-bottom: 20px;
}

.status-card {
  border-radius: 8px;
  overflow: hidden;
}

.status-card.online {
  border-left: 4px solid #67C23A;
}

.status-card.offline {
  border-left: 4px solid #F56C6C;
}

.status-card.warning {
  border-left: 4px solid #E6A23C;
}

.status-card.critical {
  border-left: 4px solid #F56C6C;
}

.card-content {
  display: flex;
  align-items: center;
  padding: 10px 0;
}

.card-content .icon {
  font-size: 32px;
  margin-right: 15px;
  color: #409EFF;
}

.card-content .info .value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.card-content .info .label {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.charts-section {
  margin-bottom: 20px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  height: 300px;
  width: 100%;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.progress-text {
  margin-left: 10px;
  font-size: 12px;
  color: #606266;
}

.host-list-section {
  margin-top: 20px;
}
</style>
